import React from 'react';

export default class PictureComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
        this.dragging = null;
        this.index = null;
        this.placeholder = document.createElement('li');
        this.placeholder.className="sortable-placeholder";
        this.placeholder.addEventListener('dragover', this.dragover)
        this.placeholder.addEventListener('drop', this.dragover)
    }

    dragover = (e) => {
        let target = e.target;
        if (e.type === 'drop') {
            e.stopPropagation();
            target.parentNode && target.parentNode.insertBefore(this.dragging, target.nextSibling)
            return false;
        }
        e.preventDefault();
    }

    ondragstart = (e) => {
        e.dataTransfer.effectAllowed = 'move';
        this.dragging = e._targetInst.type === 'li' ? e._targetInst.stateNode : e._targetInst.return.stateNode;
        this.index = e._targetInst.index;
        this.placeholder.style.width = this.dragging.offsetWidth + "px"
        this.placeholder.style.height = this.dragging.offsetHeight + "px"
    }

    ondragover = (e) => {
        let target = e._targetInst.type === 'li' ? e._targetInst.stateNode : e._targetInst.return.stateNode;
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        if(this.dragging === target) {
            target.style.display = 'none';
        }
        let placeholderIndex = this.placeholder.parentNode && [].indexOf.call(this.placeholder.parentNode.childNodes, this.placeholder);
        let targetIndex = target.parentNode && [].indexOf.call(target.parentNode.childNodes, target);
        target.parentNode.insertBefore(this.placeholder, (placeholderIndex < targetIndex ? target.nextSibling : target))
        return false;
    }

    ondragend = (e) => {
        let target = e._targetInst.type === 'li' ? e._targetInst.stateNode : e._targetInst.return.stateNode;
        target.parentNode.removeChild(this.placeholder)
        this.dragging.style.display = 'inline-block';
    }

    render() {
        let pictureEle = this.props.fileList.map(el => {
            return (
                <li 
                    key={el.Id} 

                    draggable="true"
                    onDragStart={this.ondragstart}
                    
                    onDragEnd={this.ondragend}
                    onDragOver={this.ondragover}
                    onDrop={this.ondragover}

                    data-largegrapgh={el.LargeGraph}>
                    <img src={el.Thumbnail} alt=""/>
                    <p>{el.Name}</p>
                </li>
            )
        })
        return (
            <ul className="pictureCont">
                {
                    pictureEle
                }
            </ul>
        )
    }
}